<?php
/**
 * 项目公共方法文件
 * 
 */

/**
 * 取用户IP地址
 */
function GetUserIP() {
	if (getenv ( 'HTTP_CLIENT_IP' ) && strcasecmp ( getenv ( 'HTTP_CLIENT_IP' ), 'unknown' )) {
		$IP = getenv ( 'HTTP_CLIENT_IP' );
	} elseif (getenv ( 'HTTP_X_FORWARDED_FOR' ) && strcasecmp ( getenv ( 'HTTP_X_FORWARDED_FOR' ), 'unknown' )) {
		$IP = getenv ( 'HTTP_X_FORWARDED_FOR' );
	} elseif (getenv ( 'REMOTE_ADDR' ) && strcasecmp ( getenv ( 'REMOTE_ADDR' ), 'unknown' )) {
		$IP = getenv ( 'REMOTE_ADDR' );
	} elseif (isset ( $_SERVER ['REMOTE_ADDR'] ) && $_SERVER ['REMOTE_ADDR'] && strcasecmp ( $_SERVER ['REMOTE_ADDR'], 'unknown' )) {
		$IP = $_SERVER ['REMOTE_ADDR'];
	}
	return $IP;
}

/**
 * 对数据进行编码转换
 *
 * @param $data array/string
 *       	 数组
 * @param $input string
 *       	 需要转换的编码
 * @param $output string
 *       	 转换后的编码
 */
function array_iconv($data, $input = 'gbk', $output = 'utf-8') {
	if (! is_array ( $data )) {
		return iconv ( $input, $output, $data );
	} else {
		foreach ( $data as $key => $val ) {
			if (is_array ( $val )) {
				$data [$key] = array_iconv ( $val, $input, $output );
			} else {
				$data [$key] = iconv ( $input, $output, $val );
			}
		}
		return $data;
	}
}

/*
 * 截取字符串 @param $string 要截取的字符串 @param $length 截取长度 @param $dot @return 取得到的结果集
 */
function cutstr($string, $length, $dot = ' ...') {
	$charset = 'utf-8';
	if (strlen ( $string ) <= $length) {
		return $string;
	}
	$strcut = '';
	if (strtolower ( $charset ) == 'utf-8') {
		$n = $tn = $noc = 0;
		while ( $n < strlen ( $string ) ) {
			
			$t = ord ( $string [$n] );
			if ($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
				$tn = 1;
				$n ++;
				$noc ++;
			} elseif (194 <= $t && $t <= 223) {
				$tn = 2;
				$n += 2;
				$noc += 2;
			} elseif (224 <= $t && $t < 239) {
				$tn = 3;
				$n += 3;
				$noc += 2;
			} elseif (240 <= $t && $t <= 247) {
				$tn = 4;
				$n += 4;
				$noc += 2;
			} elseif (248 <= $t && $t <= 251) {
				$tn = 5;
				$n += 5;
				$noc += 2;
			} elseif ($t == 252 || $t == 253) {
				$tn = 6;
				$n += 6;
				$noc += 2;
			} else {
				$n ++;
			}
			
			if ($noc >= $length) {
				break;
			}
		
		}
		if ($noc > $length) {
			$n -= $tn;
		}
		
		$strcut = substr ( $string, 0, $n );
	
	} else {
		for($i = 0; $i < $length - 3; $i ++) {
			$strcut .= ord ( $string [$i] ) > 127 ? $string [$i] . $string [++ $i] : $string [$i];
		}
	}
	
	return $strcut . $dot;
}

/**
 * 生成哈稀目录
 *
 * @param $n string       	
 * @param $mod_num string       	
 * @return string
 */
function getHashPath($n, $mod_num = 1999) {
	$count = ceil ( strlen ( $n ) / 3 ); // 3位叠加法
	
	$sum = 0;
	for($i = 0; $i < $count; $i ++) {
		$sum += substr ( $n, $i * 3, 3 );
	}
	$result = ( string ) ($sum % $mod_num);
	return $result;
}

/**
 * 格式化哈稀目录名（3位16进制）
 *
 * @param $path string       	
 * @return string
 */
function formatHashPath($path) {
	$_path = dechex ( $path );
	$_length = strlen ( $_path );
	if ($_length == 2) {
		$result = '0' . $_path;
	} elseif ($_length == 1) {
		$result = '00' . $_path;
	} else {
		$result = $_path;
	}
	return $result;
}

/**
 * 可以统计中英文字符数量
 *
 * @param $str string       	
 * @return $n
 */
function length($str) {
	$len = strlen ( $str );
	$i = 0;
	$n = 0;
	while ( $i < $len ) {
		if (preg_match ( "/^[" . chr ( 0xa1 ) . "-" . chr ( 0xff ) . "]+$/", $str [$i] )) {
			$i += 2;
		} else {
			$i += 1;
		}
		$n += 1;
	}
	return $n;
}

/**
 * 返回文件信息
 */
function mime_contenttype($_file_name) {
	if (! $_file_name) {
		return false;
	}
	
	$mimetypes = array (

	"ez" => "application/andrew-inset", "hqx" => "application/mac-binhex40", "cpt" => "application/mac-compactpro", "doc" => "application/msword", "bin" => "application/octet-stream", "dms" => "application/octet-stream", "lha" => "application/octet-stream", "lzh" => "application/octet-stream", "exe" => "application/octet-stream", "class" => "application/octet-stream", "so" => "application/octet-stream", "dll" => "application/octet-stream", "oda" => "application/oda", "pdf" => "application/pdf", "ai" => "application/postscript", "eps" => "application/postscript", "ps" => "application/postscript", "smi" => "application/smil", "smil" => "application/smil", "wbxml" => "application/vnd.wap.wbxml", "wmlc" => "application/vnd.wap.wmlc", "wmlsc" => "application/vnd.wap.wmlscriptc", "bcpio" => "application/x-bcpio", "vcd" => "application/x-cdlink", "pgn" => "application/x-chess-pgn", "cpio" => "application/x-cpio", "csh" => "application/x-csh", "dcr" => "application/x-director", "dir" => "application/x-director", "dxr" => "application/x-director", "dvi" => "application/x-dvi", "spl" => "application/x-futuresplash", "gtar" => "application/x-gtar", "hdf" => "application/x-hdf", "js" => "application/x-javascript", "skp" => "application/x-koan", "skd" => "application/x-koan", "skt" => "application/x-koan", "skm" => "application/x-koan", "latex" => "application/x-latex", "nc" => "application/x-netcdf", "cdf" => "application/x-netcdf", "sh" => "application/x-sh", "shar" => "application/x-shar", "swf" => "application/x-shockwave-flash", "sit" => "application/x-stuffit", "sv4cpio" => "application/x-sv4cpio", "sv4crc" => "application/x-sv4crc", "tar" => "application/x-tar", "tcl" => "application/x-tcl", "tex" => "application/x-tex", "texinfo" => "application/x-texinfo", "texi" => "application/x-texinfo", "t" => "application/x-troff", "tr" => "application/x-troff", "roff" => "application/x-troff", "man" => "application/x-troff-man", "me" => "application/x-troff-me", "ms" => "application/x-troff-ms", "ustar" => "application/x-ustar", "src" => "application/x-wais-source", "xhtml" => "application/xhtml+xml", "xht" => "application/xhtml+xml", "zip" => "application/zip", "au" => "audio/basic", "snd" => "audio/basic", "mid" => "audio/midi", "midi" => "audio/midi", "kar" => "audio/midi", "mpga" => "audio/mpeg", "mp2" => "audio/mpeg", "mp3" => "audio/mpeg", "aif" => "audio/x-aiff", "aiff" => "audio/x-aiff", "aifc" => "audio/x-aiff", "m3u" => "audio/x-mpegurl", "ram" => "audio/x-pn-realaudio", "rm" => "audio/x-pn-realaudio", "rpm" => "audio/x-pn-realaudio-plugin", "ra" => "audio/x-realaudio", "wav" => "audio/x-wav", "pdb" => "chemical/x-pdb", "xyz" => "chemical/x-xyz", "bmp" => "image/bmp", "gif" => "image/gif", "ief" => "image/ief", "jpe" => "image/jpeg", "jpeg" => "image/jpeg", "jpg" => "image/jpeg", "png" => "image/png", "tiff" => "image/tiff", "tif" => "image/tif", "djvu" => "image/vnd.djvu", "djv" => "image/vnd.djvu", "wbmp" => "image/vnd.wap.wbmp", "ras" => "image/x-cmu-raster", "pnm" => "image/x-portable-anymap", "pbm" => "image/x-portable-bitmap", "pgm" => "image/x-portable-graymap", "ppm" => "image/x-portable-pixmap", "rgb" => "image/x-rgb", "xbm" => "image/x-xbitmap", "xpm" => "image/x-xpixmap", "xwd" => "image/x-windowdump", "igs" => "model/iges", "iges" => "model/iges", "msh" => "model/mesh", "mesh" => "model/mesh", "silo" => "model/mesh", "wrl" => "model/vrml", "vrml" => "model/vrml", "css" => "text/css", "html" => "text/html", "htm" => "text/html", "asc" => "text/plain", "txt" => "text/plain", "rtx" => "text/richtext", "rtf" => "text/rtf", "sgml" => "text/sgml", "sgm" => "text/sgml", "tsv" => "text/tab-seperated-values", "wml" => "text/vnd.wap.wml", "wmls" => "text/vnd.wap.wmlscript", "etx" => "text/x-setext", "xml" => "text/xml", "xsl" => "text/xml", "mpeg" => "video/mpeg", "mpg" => "video/mpeg", "mpe" => "video/mpeg", "qt" => "video/quicktime", "mov" => "video/quicktime", "mxu" => "video/vnd.mpegurl", "avi" => "video/x-msvideo", "movie" => "video/x-sgi-movie", "ice" => "x-conference-xcooltalk", "wmv" => "video/x-ms-wmv", "wma" => "audio/x-ms-wma", "asf" => "video/x-msvideo" );
	$_file_name = urlencode ( $_file_name );
	$_file_name_arr = explode ( '.', $_file_name );
	$file_ext = $_file_name_arr [count ( $_file_name_arr ) - 1];
	unset ( $_file_name_arr [count ( $_file_name_arr ) - 1] );
	$file_name = implode ( $_file_name_arr );
	if ($mimetypes [strtolower ( $file_ext )]) {
		$file_name_arr ['mime'] = $mimetypes [strtolower ( $file_ext )];
	} else {
		$file_name_arr ['mime'] = "application/octet-stream";
	}
	$file_name_arr = array (

	'full_name' => $file_name . "." . $file_ext, 'name' => $file_name, 'ext' => strtolower ( $file_ext ), 'mime' => $file_name_arr ['mime'] );
	return $file_name_arr;
}

/**
 * 建立目录
 */
function makeDir($path_info) {
	$path = APP_PATH . $path_info . DIRECTORY_SEPARATOR;
	$path_mk = null;
	if (file_exists ( $path )) {
		return false;
	} else {
		$path_arr = explode ( DIRECTORY_SEPARATOR, $path_info );
		foreach ( $path_arr as $value ) {
			$path_mk .= $value . DIRECTORY_SEPARATOR;
			if (! file_exists ( $path_mk ))
				@mkdir ( $path_mk );
		}
		return true;
	}
}

/**
 * 设置页面标题
 * set_site_title()
 *
 * @param $title MAX       	
 */
function set_site_title($title = null, $format = null) {
	$modelSeo = new Model_Seo ();
	$modelSeo->setPageTitle ( $title, $format );
}

/**
 * 页面SEO设置
 *
 * @param $t string       	
 * @param $t_format string       	
 * @param $page_description string       	
 * @param $page_keywords string       	
 */
function set_site_seo($t, $t_format = null, $page_description = null, $page_keywords = null) {
	$modelSeo = new Model_Seo ();
	$modelSeo->setPageSeoInfo ( $t, $t_format, $page_description, $page_keywords );
}

/**
 * HTTP方式数据传输
 *
 * @param $url URL地址       	
 * @param $data 如果是POST方式赋
 *       	 $_POST 值
 * @return 取得到的结果集
 */
function http_to_host($url, $data = '', $http_header = null) {
	$url = parse_url ( $url );
	if (! $url) {
		return false;
	}
	if (! isset ( $url ['port'] )) {
		$url ['port'] = "";
	}
	if (! isset ( $url ['query'] )) {
		$url ['query'] = "";
	}
	
	$encoded = "";
	
	if (is_array ( $data )) {
		while ( list ( $k, $v ) = each ( $data ) ) {
			$encoded .= ($encoded ? "&" : "");
			$encoded .= rawurlencode ( $k ) . "=" . rawurlencode ( $v );
		}
		$type = 'post';
	}
	
	$fp = @fsockopen ( $url ['host'], $url ['port'] ? $url ['port'] : 80, $errno, $errstr, 15 );
	if (! $fp) {
		@fclose ( $fp );
		return false;
	}
	
	if ($type == 'post') {
		fputs ( $fp, sprintf ( "POST %s%s%s HTTP/1.0\n", $url ['path'], $url ['query'] ? "?" : "", $url ['query'] ) );
		fputs ( $fp, "Host: $url[host]\n" );
		fputs ( $fp, "Content-type: application/x-www-form-urlencoded\n" );
		fputs ( $fp, "Content-length: " . strlen ( $encoded ) . "\n" );
		if (is_array ( $http_header )) {
			foreach ( $http_header as $key => $value ) {
				fputs ( $fp, $key . ": " . $value );
			}
		}
		
		fputs ( $fp, "Connection: close\n\n" );
	} else {
		fputs ( $fp, sprintf ( "GET %s%s%s HTTP/1.1\n", $url ['path'], $url ['query'] ? "?" : "", $url ['query'] ) );
		fputs ( $fp, "Host: $url[host]\n" );
		if (is_array ( $http_header )) {
			foreach ( $http_header as $key => $value ) {
				fputs ( $fp, $key . ": " . $value );
			}
		}
		fputs ( $fp, "Connection: Close\n\n" );
	}
	
	fputs ( $fp, "$encoded\n" );
	
	// $line = fgets($fp,1024);
	// if (!eregi("^HTTP/1\.. 200", $line)) return;
	
	$results = "";
	$inheader = 1;
	while ( ! feof ( $fp ) ) {
		$line = @fgets ( $fp, 1024 );
		// dump($line);
		if ($inheader && ($line == "\n" || $line == "\r\n")) {
			$inheader = 0;
		} elseif (! $inheader) {
			$results .= $line;
		}
	}
	@fclose ( $fp );
	
	return $results;
}

/**
 * 随机字符串
 *
 * @param $length unknown_type       	
 * @param $numeric unknown_type       	
 * @return unknown
 */
function random($length, $numeric = 0) {
	mt_srand ( ( double ) microtime () * 1000000 );
	if ($numeric) {
		$hash = sprintf ( '%0' . $length . 'd', mt_rand ( 0, pow ( 10, $length ) - 1 ) );
	} else {
		$hash = '';
		$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
		$max = strlen ( $chars ) - 1;
		for($i = 0; $i < $length; $i ++) {
			$hash .= $chars [mt_rand ( 0, $max )];
		}
	}
	return $hash;
}

/**
 * 将一个数组转码
 *
 * @param $source array       	
 * @param $to unknown_type       	
 * @param $array unknown_type       	
 * @return unknown
 */
function iconv_array($source, $to, $array) {
	$xml_arr = array ();
	foreach ( $array as $array_key => $array_val ) {
		if (is_array ( $array_val )) {
			$xml_arr [mb_convert_encoding ( $array_key, $to, $source )] = iconv_array ( $source, $to, $array_val );
		} else {
			$xml_arr [mb_convert_encoding ( $array_key, $to, $source )] = trim ( mb_convert_encoding ( $array_val, $to, $source ) );
		}
	}
	return $xml_arr;
}

/**
 * 解密、加密
 *
 * @param $string string       	
 * @param $operation method       	
 * @param $key string       	
 * @return string
 */
function encryption($string, $operation, $key = '') {
	$key = md5 ( $key );
	$key_length = strlen ( $key );
	
	$string = $operation == 'DECODE' ? base64_decode ( $string ) : substr ( md5 ( $string . $key ), 0, 8 ) . $string;
	$string_length = strlen ( $string );
	
	$rndkey = $box = array ();
	$result = '';
	
	for($i = 0; $i <= 255; $i ++) {
		$rndkey [$i] = ord ( $key [$i % $key_length] );
		$box [$i] = $i;
	}
	
	for($j = $i = 0; $i < 256; $i ++) {
		$j = ($j + $box [$i] + $rndkey [$i]) % 256;
		$tmp = $box [$i];
		$box [$i] = $box [$j];
		$box [$j] = $tmp;
	}
	
	for($a = $j = $i = 0; $i < $string_length; $i ++) {
		$a = ($a + 1) % 256;
		$j = ($j + $box [$a]) % 256;
		$tmp = $box [$a];
		$box [$a] = $box [$j];
		$box [$j] = $tmp;
		$result .= chr ( ord ( $string [$i] ) ^ ($box [($box [$a] + $box [$j]) % 256]) );
	}
	
	if ($operation == 'DECODE') {
		if (substr ( $result, 0, 8 ) == substr ( md5 ( substr ( $result, 8 ) . $key ), 0, 8 )) {
			return substr ( $result, 8 );
		} else {
			return '';
		}
	} else {
		return str_replace ( '=', '', base64_encode ( $result ) );
	}
}

/**
 * 过滤字符串中的所有的HTML代码，以及非法的全角符号
 */
function striptags_pro($str) {
	$str = strip_tags ( $str );
	$str = preg_replace ( "/(　)/", "", $str );
	return $str;
}

/**
 * 将DATETIME转换为UNIX时间戳
 *
 * @param $time unknown_type       	
 * @return unknown
 */
function datetime2stamp($time) {
	return mktime ( substr ( $time, 11, 2 ), substr ( $time, 14, 2 ), substr ( $time, 17, 2 ), substr ( $time, 5, 2 ), substr ( $time, 8, 2 ), substr ( $time, 0, 4 ) );
}

/**
 * 数组转换为json
 */
function jsonencode($array) {
	if ($array && is_array ( $array )) {
		$json_str = "{";
		$arrlength = 1;
		foreach ( $array as $key => $val ) {
			$json_str .= "\"" . $key . "\":";
			if (is_string ( $val )) {
				$json_str .= "\"" . $val . "\"";
			} elseif (is_bool ( $val )) {
				$val ? $json_str .= "true" : $json_str .= "false";
			} elseif (is_numeric ( $val )) {
				$json_str .= $val;
			} elseif (is_array ( $val )) {
				$json_str .= "[" . jsonencode ( $val ) . "]";
			} elseif (! $val) {
				$json_str .= "null";
			}
			
			if (count ( $array ) != $arrlength) {
				$json_str .= ",";
			}
			$arrlength ++;
		}
		$json_str .= "}";
	}
	return $json_str;
}

/**
 * curl
 *
 * @param $url URL地址       	
 * @param $param['cookie_file'] =>
 *       	 cookie文件路径
 * @param $param['cookie_type'] =>
 *       	 cookie访问类型(read为读，write为写)
 * @param $method post，get方式       	
 * @param $param['fields'] =>
 *       	 传递参数
 * @param $param['user_agent'] =>
 *       	 在HTTP请求中包含一个"user-agent"头的字符串
 * @param $param['timeout'] =>
 *       	 超时限制默认60秒
 * @param $param['referer'] =>
 *       	 referer值
 */
function curl_string($url, $method = 'get', $param = array()) {
	$ch = curl_init ();
	curl_setopt ( $ch, CURLOPT_URL, $url );
	if (! empty ( $param ['cookie_file'] ) && $param ['cookie_type'] == 'read') { // 读取cookie文件
		curl_setopt ( $ch, CURLOPT_COOKIEFILE, $param ['cookie_file'] );
	}
	curl_setopt ( $ch, CURLOPT_HEADER, 0 );
	if ($method == 'post') {
		curl_setopt ( $ch, CURLOPT_POST, 1 );
	} elseif ($method == 'get') {
		curl_setopt ( $ch, CURLOPT_HTTPGET, 1 );
	}
	if (! empty ( $param ['fields'] )) { // 参数
		curl_setopt ( $ch, CURLOPT_POSTFIELDS, $param ['fields'] );
	}
	curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
	curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );
	curl_setopt ( $ch, CURLOPT_FOLLOWLOCATION, 1 );
	if (! empty ( $param ['cookie_file'] ) && $param ['cookie_type'] == 'write') { // 写cookie文件
		curl_setopt ( $ch, CURLOPT_COOKIEJAR, $param ['cookie_file'] );
	}
	if (! empty ( $param ['user_agent'] )) {
		curl_setopt ( $ch, CURLOPT_USERAGENT, $param ['user_agent'] );
	}
	if (! empty ( $param ['timeout'] )) {
		curl_setopt ( $ch, CURLOPT_TIMEOUT, $param ['timeout'] );
	}
	if (! empty ( $param ['referer'] )) {
		curl_setopt ( $ch, CURLOPT_REFERER, $param ['referer'] );
	}
	$res = curl_exec ( $ch );
	curl_close ( $ch );
	
	return $res;
}

/**
 * 返回附件类型图标
 *
 * @param $file 附件名称       	
 * @param $type png为大图标，gif为小图标       	
 */
function file_icon($file, $type = 'png') {
	$ext_arr = array ('doc', 'docx', 'ppt', 'xls', 'txt', 'pdf', 'mdb', 'jpg', 'gif', 'png', 'bmp', 'jpeg', 'rar', 'zip', 'swf', 'flv' );
	$ext = fileext ( $file );
	if ($type == 'png') {
		if ($ext == 'zip' || $ext == 'rar')
			$ext = 'rar';
		elseif ($ext == 'doc' || $ext == 'docx')
			$ext = 'doc';
		elseif ($ext == 'xls' || $ext == 'xlsx')
			$ext = 'xls';
		elseif ($ext == 'ppt' || $ext == 'pptx')
			$ext = 'ppt';
		elseif ($ext == 'flv' || $ext == 'swf' || $ext == 'rm' || $ext == 'rmvb')
			$ext = 'flv';
		else
			$ext = 'do';
	}
	$config = Zend_Registry::get ( 'config' );
	if (in_array ( $ext, $ext_arr ))
		return $config->view_conf->siteImgPath . '/ext/' . $ext . '.' . $type;
	else
		return $config->view_conf->siteImgPath . '/ext/blank.' . $type;
}

/**
 * 取得文件扩展
 *
 * @param $filename 文件名       	
 * @return 扩展名
 */
function fileext($filename) {
	return strtolower ( trim ( substr ( strrchr ( $filename, '.' ), 1, 10 ) ) );
}

/**
 * 转换字节数为其他单位
 *
 *
 * @param $filesize string       	
 * @return string
 */
function sizecount($filesize) {
	if ($filesize >= 1073741824) {
		$filesize = round ( $filesize / 1073741824 * 100 ) / 100 . ' GB';
	} elseif ($filesize >= 1048576) {
		$filesize = round ( $filesize / 1048576 * 100 ) / 100 . ' MB';
	} elseif ($filesize >= 1024) {
		$filesize = round ( $filesize / 1024 * 100 ) / 100 . ' KB';
	} else {
		$filesize = $filesize . ' Bytes';
	}
	return $filesize;
}

/**
 * 显示调试信息
 *
 * @param $vars unknown_type       	
 * @param $label unknown_type       	
 * @param $return unknown_type       	
 * @return unknown
 */
function dump($vars, $label = '', $return = false) {
	if (ini_get ( 'html_errors' )) {
		$content = "<pre>\n";
		if ($label != '') {
			$content .= "<strong>{$label} :</strong>\n";
		}
		$content .= htmlspecialchars ( print_r ( $vars, true ) );
		$content .= "\n</pre>\n";
	} else {
		$content = $label . " :\n" . print_r ( $vars, true );
	}
	if ($return) {
		return $content;
	}
	echo $content;
	return null;
}

?>